from flask import Flask, render_template, request, jsonify
from datetime import datetime, timedelta
import json
import os
from threading import Lock

app = Flask(__name__)

# 文件存储配置
DATA_FILE = 'pixels.json'
file_lock = Lock()

def load_pixels():
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r') as f:
            return json.load(f)
    return {}

def save_pixels(data):
    with file_lock:
        with open(DATA_FILE, 'w') as f:
            json.dump(data, f)

pixels = load_pixels()
user_cooldown = {}

# 画板尺寸和像素大小
BOARD_SIZE = 50
PIXEL_SIZE = 50

@app.route('/')
def index():
    return render_template('index.html', 
                         board_size=BOARD_SIZE,
                         pixel_size=PIXEL_SIZE)

@app.route('/get_pixels')
def get_pixels():
    return jsonify(pixels)

@app.route('/update_pixel', methods=['POST'])
def update_pixel():
    data = request.json
    x, y = data['x'], data['y']
    color = data['color'].upper()
    
    # 颜色格式验证
    if not (len(color) == 7 and color.startswith('#')) and \
       not (len(color) == 4 and color.startswith('#')):
        return jsonify(status="invalid color"), 400
    
    user_ip = request.remote_addr

    # 冷却时间验证
    last_time = user_cooldown.get(user_ip)
    if last_time and datetime.now() < last_time + timedelta(seconds=5):
        return jsonify(status="cooldown", 
                      remaining=(last_time + timedelta(seconds=5) - datetime.now()).seconds), 429

    # 更新像素和冷却时间
    pixels[f"{x}-{y}"] = color
    user_cooldown[user_ip] = datetime.now()

    # 更新数据并保存
    save_pixels(pixels)
    
    return jsonify(status="success")

if __name__ == '__main__':
    app.run(debug=True)